//
// Created by Administrator on 2021/11/11.
// May Saint Diana bless you!
//
#include <iostream>
#include <vector>

using namespace std;

class Solution {
public:
    vector<vector<int>> movements{{0,  1},
                                  {1,  0},
                                  {0,  -1},
                                  {-1, 0}}; // 东 南  西 北
    vector<vector<int>> spiralMatrixIII(int rows, int cols, int rStart, int cStart) {
        vector<vector<int>> ans;
        ans.emplace_back(vector<int>{rStart, cStart});
        int counter = 1, target = rows * cols; // 记录走过了多少个格子,需要走多少个格子
        int loop = 2; // 控制方向和步长
        int r = rStart, c = cStart; // 当前位置
        while (counter < target) {
            // 每段路径 包含尾部不含头部
            int dr = movements[(loop - 2) % 4][0], dc = movements[(loop - 2) % 4][1];
            for (int i = 0; i < loop / 2; ++i) { // 长度变化：1 1 2 2 3 3 。。。
                r += dr;
                c += dc;
                if (r >= 0 and r < rows and c >= 0 and c < cols) {
                    ans.emplace_back(vector<int>{r, c});
                    ++counter;
                }
            }
            ++loop;
        }
        return ans;
    }
};

int main() {
    Solution solution;
    vector<vector<int>> ans = solution.spiralMatrixIII(5, 6, 1, 4);
    for (const auto &row:ans) {
        for (const auto &x:row) {
            cout << x << " ";
        }
        cout << endl;
    }
    return 0;
}


